package com.nativetalk.controller.app.teacher.apply;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.authentication.TdNtAuthenticationInsertTwo;
import com.nativetalk.bean.course.TdNtCoursePictureList;
import com.nativetalk.bean.course.TsNtCourseInfoTeacher;
import com.nativetalk.bean.dict.TsNtDictIndex;
import com.nativetalk.bean.dict.TsNtDictTea;
import com.nativetalk.bean.member.TdNtMemberDetail;
import com.nativetalk.bean.study.TdNtStudyTeachDetail;
import com.nativetalk.bean.teacher.TdNtTeacherLogin;
import com.nativetalk.bean.teacher.TdNtTeacherPayPal;
import com.nativetalk.bean.teacher.TdNtTeacherResult;
import com.nativetalk.bean.teacher.TdNtTeacherState;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.getui.AndroidStudentGetui;
import com.nativetalk.common.getui.IosStudentGetui;
import com.nativetalk.common.util.Ip;
import com.nativetalk.common.util.JsonUtil;
import com.nativetalk.common.util.MemcachedKey;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.service.authentication.insert.AuthenticationInsertService;
import com.nativetalk.service.member.search.MemberSearchService;
import com.nativetalk.service.study.search.StudyTeachService;
import com.nativetalk.service.teacher.login.TeacherLoginService;
import com.nativetalk.service.teacher.update.TeacherUpdateService;
import com.nativetalk.service.three.course.CourseService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lizhun on 15/12/9.
 */
@Controller
public class ApplyController {
    private static Logger logger = Logger.getLogger(ApplyController.class);
    @Resource
    private AuthenticationInsertService authenticationInsertService;
    @Resource
    private TeacherUpdateService teacherUpdateService;
    @Resource
    private TeacherLoginService teacherLoginService;
    @Resource
    private StudyTeachService studyTeachService;
    @Resource
    private MemberSearchService memberSearchService;
    @Resource
    private CourseService courseService;

    /**
     * @Purpose  获取学校信息
     * @version  1.0
     * @time     2015-12-25
     * @author   lizhun
     * @return   RetInfo
     */
    @RequestMapping(value="/app/2/teatoken/apply/university" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json")
    @ResponseBody
    public RetInfo university() {
        RetInfo retInfo = new RetInfo();
        Map<String , Object> map = new HashMap<>();
        try {
            //打印入参
            logger.info(Constants.prefix_in);

            List<TsNtDictTea> university = (List<TsNtDictTea>) MemcachedUtils.get(MemcachedKey.tsNtDictTeas);
            map.put("university" , university);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取大学数据成功");
            retInfo.setObj(map);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @Purpose  申请认证
     * @version  1.0
     * @time     2015-01-11
     * @author   lizhun
     * @param     tdNtAuthenticationInsert
     * @return   RetInfo
     */
    @RequestMapping(value="/app/2/teatoken/teacher/apply" ,method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public RetInfo apply(@Valid @ModelAttribute TdNtAuthenticationInsertTwo tdNtAuthenticationInsert, BindingResult result,
                         @RequestHeader(value = "token", required = true) String token) throws IOException {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err=result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        }else {
            try {
                //打印入参
                logger.info(Constants.prefix_in + JsonUtil.toJson(tdNtAuthenticationInsert));

                TdNtTeacherResult tdNtTeacherResult = (TdNtTeacherResult) MemcachedUtils.get(token);
                tdNtAuthenticationInsert.setTea_id(tdNtTeacherResult.getTea_id());
                retInfo =  authenticationInsertService.insertAuthenticationTwo(tdNtAuthenticationInsert);

                //打印出参
                logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            } catch (Exception e) {
                //记录错误日志
                retInfo = RetInfo.getServerErrorInfo();
                logger.error(e.getMessage(), e);

                //打印出参
                logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            }

        }
        return retInfo;
    }

    /**
     * @Purpose  教学开关
     * @version  1.0
     * @time     2015-01-09
     * @author   lizhun
     * @param    token
     * @return   RetInfo
     */
    @RequestMapping(value = "/app/2/teatoken/teacher/state" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json; charset=utf-8" )
    @ResponseBody
    public RetInfo state(@Valid @RequestBody TdNtTeacherState tdNtTeacherState, BindingResult result,
                         @RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err=result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        }else {
            try {
                //打印入参
                logger.info(Constants.prefix_in + JsonUtil.toJson(tdNtTeacherState));

                TdNtTeacherResult tdNtTeacherResult = (TdNtTeacherResult) MemcachedUtils.get(token);
                tdNtTeacherState.setTea_id(tdNtTeacherResult.getTea_id());
                if(Constants.Teacher.State.online.equals(tdNtTeacherState.getState())){
                    tdNtTeacherState.setState_order(Constants.Teacher.StateOrder.online);
                }
                else if(Constants.Teacher.State.offline.equals(tdNtTeacherState.getState())){
                    tdNtTeacherState.setState_order(Constants.Teacher.StateOrder.offline);
                }
                retInfo = teacherUpdateService.updateTeacherStateTwo(tdNtTeacherState);

                //打印出参
                logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            } catch (Exception e) {
                //记录错误日志
                retInfo = RetInfo.getServerErrorInfo();
                logger.error(e.getMessage(), e);

                //打印出参
                logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            }

        }
        return retInfo;
    }
    /**
     * @Purpose  教学开关(新)
     * @version  1.0
     * @time     2016/4/18
     * @author   wuyuanhui
     * @Modifier wangzheng on 2017/03/24
     * @param    token
     * @return   RetInfo
     */
    @RequestMapping(value = "/app/3/teatoken/teacher/state" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json; charset=utf-8" )
    @ResponseBody
    public RetInfo stateThree(@Valid @RequestBody TdNtTeacherState tdNtTeacherState, BindingResult result,
                         @RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err=result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        }else {
            try {
                //打印入参
                logger.info(Constants.prefix_in + JsonUtil.toJson(tdNtTeacherState));

                TdNtTeacherResult tdNtTeacherResult = (TdNtTeacherResult) MemcachedUtils.get(token);
                tdNtTeacherState.setTea_id(tdNtTeacherResult.getTea_id());
                //根据老师的状态更新老师的状态排序
                if(Constants.Teacher.State.online.equals(tdNtTeacherState.getState())){
                    tdNtTeacherState.setState_order(Constants.Teacher.StateOrder.online);
                }
                else if(Constants.Teacher.State.offline.equals(tdNtTeacherState.getState())){
                    tdNtTeacherState.setState_order(Constants.Teacher.StateOrder.offline);
                }
                retInfo = teacherUpdateService.updateTeacherStateThree(tdNtTeacherState);

                //打印出参
                logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            } catch (Exception e) {
                //记录错误日志
                retInfo = RetInfo.getServerErrorInfo();
                logger.error(e.getMessage(), e);

                //打印出参
                logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            }

        }
        return retInfo;
    }

    /**
     * @Purpose  获取类别下课程信息
     * @version  1.0
     * @time     2015-12-25
     * @author   lizhun
     * @return   RetInfo
     */
    @RequestMapping(value="/app/2/teatoken/category/course" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json")
    @ResponseBody
    public RetInfo course(@RequestBody Map<String, String> mapParam) {
        RetInfo retInfo = new RetInfo();
        Map<String , Object> map = new HashMap<>();
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(mapParam));

            Map<String, List<TsNtCourseInfoTeacher>> tsNtCourseInfoTeachersMap =
                    (Map<String, List<TsNtCourseInfoTeacher>>)MemcachedUtils.get(MemcachedKey.tsNtCourseInfoTeachersMap);
            map.put("courses" , tsNtCourseInfoTeachersMap.get(mapParam.get("cate_id")));
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取课程信息成功");
            retInfo.setObj(map);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @Purpose  获取类别下课程信息(前五张教材)
     * @version  1.0
     * @time     2015-12-25
     * @author   lizhun
     * @return   RetInfo
     */
    @RequestMapping(value="/app/2/teatoken/category/course/picture" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json")
    @ResponseBody
    public RetInfo picture(@RequestBody Map<String, String> mapParam) {
        RetInfo retInfo = new RetInfo();
        Map<String , Object> map = new HashMap<>();
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(mapParam));

            List<TdNtCoursePictureList> pictures = courseService.findCoursePicture(mapParam.get("cou_id"));

            map.put("pictures" , pictures);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取预览教材成功");
            retInfo.setObj(map);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @Purpose  填写学校
     * @version  1.0
     * @time     2015-01-09
     * @author   lizhun
     * @param    token
     * @return   RetInfo
     */
    @RequestMapping(value = "/app/2/teatoken/teacher/updateNniversity" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json; charset=utf-8" )
    @ResponseBody
    public RetInfo updateName(@RequestBody Map<String, String> mapParam,
                              @RequestHeader(value = "token", required = true) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(mapParam));

            RetInfo retInfo;
            TdNtTeacherResult tdNtTeacherResult = (TdNtTeacherResult) MemcachedUtils.get(token);
            tdNtTeacherResult.setDict_id(mapParam.get("dict_id"));
            retInfo = teacherUpdateService.updateTeacher(tdNtTeacherResult);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @Purpose  修改简介
     * @version  1.0
     * @time     2015-01-09
     * @author   lizhun
     * @param    token
     * @return   RetInfo
     */
    @RequestMapping(value = "/app/2/teatoken/teacher/updatePayPal" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json; charset=utf-8" )
    @ResponseBody
    public RetInfo updateSynopis(@Valid @RequestBody TdNtTeacherPayPal tdNtTeacherPayPal  , BindingResult result,
                                 @RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors())   {
            List<FieldError> err=result.getFieldErrors();
            FieldError    fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        }else {
            try {
                //打印入参
                logger.info(Constants.prefix_in + JsonUtil.toJson(tdNtTeacherPayPal));

                TdNtTeacherResult tdNtTeacherResult = (TdNtTeacherResult) MemcachedUtils.get(token);
                tdNtTeacherResult.setPayPal(tdNtTeacherPayPal.getPayPal());
                retInfo = teacherUpdateService.updateTeacher(tdNtTeacherResult);

                //打印出参
                logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            } catch (Exception e) {
                //记录错误日志
                retInfo = RetInfo.getServerErrorInfo();
                logger.error(e.getMessage(), e);

                //打印出参
                logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            }
        }
        return retInfo;
    }

    /**
     * @Purpose  教学翻页
     * @version  1.0
     * @time     2015-01-09
     * @author   lizhun
     * @param    token
     * @return   RetInfo
     */
    @RequestMapping(value = "/app/2/teatoken/study/picture" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json; charset=utf-8" )
    @ResponseBody
    public RetInfo picture(@RequestBody Map<String, String> mapParam,
                              @RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
//        mapParam.get("pic_id");
//        mapParam.get("size");
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(mapParam));

            int memb_id = 0;
            if (mapParam.get("stt_id") != null) {
                TdNtTeacherResult tdNtTeacherResult = (TdNtTeacherResult) MemcachedUtils.get(token);
                TdNtStudyTeachDetail tdNtStudyTeachDetail = studyTeachService.findStudyTeachByTeaId(tdNtTeacherResult.getTea_id());
                if (MemcachedUtils.get(tdNtStudyTeachDetail.getStt_id().toString()) != null) {
                    MemcachedUtils.replace(tdNtStudyTeachDetail.getStt_id()+"",mapParam.get("size"),10*60*60);
                } else {
                    MemcachedUtils.add(tdNtStudyTeachDetail.getStt_id()+"",mapParam.get("size"),10*60*60);
                }
                memb_id = studyTeachService.findMembIdBySttId(tdNtStudyTeachDetail.getStt_id());
            } else {
                if (MemcachedUtils.get(mapParam.get("stt_id")) != null) {
                    MemcachedUtils.replace(mapParam.get("stt_id"),mapParam.get("size"),10*60*60);
                } else {
                    MemcachedUtils.add(mapParam.get("stt_id"),mapParam.get("size"),10*60*60);
                }
                memb_id = studyTeachService.findMembIdBySttId(Integer.valueOf(mapParam.get("stt_id")));
            }

            /**
             * 发推送
             */
            TdNtMemberDetail tdNtMemberDetail = memberSearchService.findTdNtMemberDetail(memb_id);
            if (tdNtMemberDetail != null) {
                if (tdNtMemberDetail.getEqu_client_id() != null && !(tdNtMemberDetail.getEqu_client_id().equals(Constants.default_equ_id))) {
                    if (tdNtMemberDetail.getEqu_type().equals("1")) {
                        AndroidStudentGetui.Flip("外教君","",tdNtMemberDetail.getEqu_client_id(),mapParam.get("size"));
                    } else {
                        IosStudentGetui.Flip("外教君","",tdNtMemberDetail.getEqu_client_id(),mapParam.get("size"));

                    }

                }
            }

            retInfo.setMark("0");
            retInfo.setTip("成功");

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @Purpose  获取个人资料
     * @version  1.0
     * @time     2015-01-09
     * @author   lizhun
     * @param    token
     * @return   RetInfo
     */
    @RequestMapping(value = "/app/2/teatoken/teacher/data" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json; charset=utf-8" )
    @ResponseBody
    public RetInfo data(@RequestHeader(value = "token", required = true) String token) {
        RetInfo retInfo = new RetInfo();
        Map<String , Object> map = new HashMap<>();
        try {
            //打印入参
            logger.info(Constants.prefix_in);

            TdNtTeacherResult tdNtTeacherResult = (TdNtTeacherResult) MemcachedUtils.get(token);
            map.put("tea_sound_synopsis" , tdNtTeacherResult.getTea_sound_synopsis());
            map.put("tea_name" , tdNtTeacherResult.getTea_name());
            map.put("tea_email" , tdNtTeacherResult.getTea_email());
            map.put("tea_sex" , tdNtTeacherResult.getTea_sex());
            map.put("tea_birthday" , tdNtTeacherResult.getTea_birthday());
            map.put("tea_synopsis" , tdNtTeacherResult.getTea_synopsis());
            map.put("tea_head_portrait" , tdNtTeacherResult.getTea_head_portrait());
            map.put("payPal" , tdNtTeacherResult.getPayPal());
            Map<String, TsNtDictIndex> tsNtDictIndicesMap = (Map<String, TsNtDictIndex>)MemcachedUtils.get(MemcachedKey.tsNtDictIndicesMap);
            if (tdNtTeacherResult.getDict_id() != null){
                map.put("university" , tsNtDictIndicesMap.get(tdNtTeacherResult.getDict_id()).getCode_eng_name());
            } else {
                map.put("university" , null);
            }
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取个人资料成功");
            retInfo.setObj(map);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @Purpose  登录
     * @version  1.0
     * @time     2015-01-07
     * @author   lizhun
     * @param    tdNtTeacherLogin
     * @return   RetInfo
     */
    @RequestMapping(value = "/app/2/teacher/login" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json; charset=utf-8" )
    @ResponseBody
    public RetInfo login(@Valid @RequestBody TdNtTeacherLogin tdNtTeacherLogin, BindingResult result,
                         @RequestHeader(value = "client_type", required = true) String client_type,
                         @RequestHeader(value = "version", required = true) Integer version) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors())   {
            List<FieldError> err=result.getFieldErrors();
            FieldError    fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        }else {
            try {
                //打印入参
                logger.info(Constants.prefix_in + JsonUtil.toJson(tdNtTeacherLogin));

                if (version >= 6) {
                    tdNtTeacherLogin.setEqu_type(client_type);
                    retInfo = teacherLoginService.loginNew(tdNtTeacherLogin);
                } else {
                    retInfo.setMark("1");
                    retInfo.setTip("We updated a new version! Check it out! ");
                }

                //打印出参
                logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            } catch (Exception e) {
                //记录错误日志
                retInfo = RetInfo.getServerErrorInfo();
                logger.error(e.getMessage(), e);

                //打印出参
                logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            }
        }
        return retInfo;
    }

    /**
     * @Purpose  登录
     * @version  2.1
     * @time     2015-05-21
     * @author   lizhun
     * @param    tdNtTeacherLogin
     * @return   RetInfo
     */
    @RequestMapping(value = "/app/5/teacher/login" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json; charset=utf-8" )
    @ResponseBody
    public RetInfo loginTwo(HttpServletRequest request, @Valid @RequestBody TdNtTeacherLogin tdNtTeacherLogin, BindingResult result,
                            @RequestHeader(value = "client_type", required = true) String client_type,
                            @RequestHeader(value = "version", required = true) Integer version) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err=result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark(ValidationMessages.getValue("MARKPARAMETERERROR"));
            retInfo.setTip(fe.getDefaultMessage());
        }else {
            try {
                //打印入参
                logger.info(Constants.prefix_in + JsonUtil.toJson(tdNtTeacherLogin));

                if (version >= 5) {
                    tdNtTeacherLogin.setEqu_type(client_type);
                    retInfo = teacherLoginService.loginTWO(tdNtTeacherLogin,version, Ip.getIpAddr(request));
                } else {
                    retInfo.setMark("1");
                    retInfo.setTip("We updated a new version! Check it out! ");
                }

                //打印出参
                logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            } catch (Exception e) {
                //记录错误日志
                retInfo = RetInfo.getServerErrorInfo();
                logger.error(e.getMessage(), e);

                //打印出参
                logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
                return retInfo;
            }
        }
        return retInfo;
    }

}